package com.qxkj.wit.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by Administrator on 2021/1/15.
 */
@Component
@ServerEndpoint("/chatServer/{roomId}")
public class ChatServer {
    // 是原型的，只要一个客户端连接，就生成一个OnlineServer对象
    // OnlineServer和客户端如何交互的呢？  session
    private Session session;

    private static CopyOnWriteArrayList<ChatServer> clients = new CopyOnWriteArrayList<>();
    private static ConcurrentHashMap<String,CopyOnWriteArrayList<OnlineServer>> rooms=new ConcurrentHashMap<String,CopyOnWriteArrayList<OnlineServer>>();
    private static ConcurrentHashMap<String,Integer> chlientsCount=new ConcurrentHashMap<String,Integer>();

    // 当一个连接对象过来时，会调用
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        clients.add(this);

        System.out.println("一个客户端连接....");

    }
    // 当一个客户端断开连接时
    @OnClose
    public void onClose(){
        clients.remove(this);

        System.out.println("一个客户端断开....");
    }

    // 当一个客户端发消息时
    @OnMessage
    public void onMessage(String msg , @PathParam("roomId") String roomId, Session session){

        for (ChatServer client : clients) {
            try {
                client.session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("接受消息....,当前房间号："+roomId);
    }

}

//直播间管理
// 创建一个房间   token
//  开播

